package se.sweco.ws.impl;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GeoDataParser {
	public static List<Route> parseRoutes(String filename) {
		List<Route> routes = new ArrayList<Route>();
		
		BufferedReader file = null;
		try {
			file = new BufferedReader(new FileReader(filename));
		} catch (FileNotFoundException e) {
			System.err.println(e.toString());
		}
		
		String line = null;
		try {
			while ((line = file.readLine()) != null) {
				String[] data = line.split(";");

				if (data.length != 3) {
					System.err.println("Invalid geo data file!");
					continue;
				}
				int routeId = Integer.parseInt(data[1]);
				Route currRoute = getRoute(routeId, routes);
				if (currRoute == null) {
					currRoute = new Route(routeId);
					routes.add(currRoute);
				}
				Coord coord = getCoord(data[2]);
				if (coord != null) {
					currRoute.addCoord(coord);
				}
			}
		} catch (NumberFormatException e) {
			System.err.println("Invalid geo data file!");
		} catch (IOException e) {
			System.err.println("Invalid geo data file!");
		}

		return routes;
	}

	private static Coord getCoord(String point) {
		String[] data = point.substring("\"POINT(".length(), point.length()-2).split(" ");
		if (data.length != 2) {
			System.err.println("Invalid geo data file!");
			return null;
		}
		double lon = Double.parseDouble(data[0]);
		double lat = Double.parseDouble(data[1]);
		
		return new Coord(lon, lat);
	}

	private static Route getRoute(int routeId, List<Route> routes) {
		for (Route route : routes) {
			if (route.getRouteId() == routeId) {
				return route;
			}
		}
		return null;
	}
}
